using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FizzyBubbles : MonoBehaviour
{
	private Liquid liquid;

	private Vector3 startPosition;

	private Vector3 maxPosition;

	private Vector3 graveyardPosition = new Vector3(1000f, 1000f, -1000f);

	private List<Transform> objectsPool;

	private List<Transform> graveyard;

	private int targetObjectsInPool = 5;

	private void Awake()
	{
		liquid = GetComponent<Liquid>();
		startPosition = liquid.transform.position;
		maxPosition = startPosition + Vector3.up * liquid.GetRawHeight();
	}

	private void PopulateGraveyard()
	{
		objectsPool = new List<Transform>();
		graveyard = new List<Transform>();
		GameObject original = Resources.Load("Prefabs/Liquids/FizzyBubble") as GameObject;
		for (int i = 0; i < 15; i++)
		{
			GameObject gameObject = UnityEngine.Object.Instantiate(original, graveyardPosition, default(Quaternion));
			gameObject.GetComponent<MeshRenderer>().sortingOrder = -1;
			graveyard.Add(gameObject.transform);
		}
	}

	public void CheckIfLiquidIsFizzy(LiquidType liquidType)
	{
		if (LiquidTypes.IsFizzy(liquidType))
		{
			PopulateGraveyard();
			StartCoroutine(MakeBubbles());
		}
		else
		{
			UnityEngine.Object.Destroy(this);
		}
	}

	private void Update()
	{
		maxPosition = startPosition + Vector3.up * liquid.GetRawHeight();
		if (objectsPool == null)
		{
			return;
		}
		int num = 0;
		while (num < objectsPool.Count)
		{
			Vector3 position = objectsPool[num].position;
			if (position.y < maxPosition.y)
			{
				objectsPool[num].position += Vector3.up * 3f * Time.deltaTime;
				num++;
			}
			else
			{
				objectsPool[num].position = graveyardPosition;
				graveyard.Add(objectsPool[num]);
				objectsPool.Remove(objectsPool[num]);
			}
		}
	}

	private IEnumerator MakeBubbles()
	{
		while (true)
		{
			float randomTime = UnityEngine.Random.Range(0.1f, 0.3f);
			yield return new WaitForSeconds(randomTime);
			Transform bubble = graveyard[0];
			bubble.position = CalculateRandomStartPosition();
			objectsPool.Add(bubble);
			graveyard.RemoveAt(0);
		}
	}

	private Vector3 CalculateRandomStartPosition()
	{
		Vector3 result = default(Vector3);
		float rawWidth = liquid.GetRawWidth();
		result.x = UnityEngine.Random.Range(startPosition.x - rawWidth * 0.5f, startPosition.x + rawWidth * 0.5f);
		result.y = startPosition.y;
		result.z = startPosition.z;
		return result;
	}
}
